const express = require('express');
const Router = express.Router();
const utils = require('utility');
const User = require('./model').getModel('user');
const Chat = require('./model').getModel('chat');

const _filter = {'pwd':0,'__v':0};
const md5Pwd = function(pwd){
	const salt = 'freedemons_1995';
	return utils.md5(utils.md5(pwd+salt));
}

Router.get('/list',function(req,res){
	const type = req.query.type;
	const select = type ? {type} : {};
	
	User.find(select,_filter,function(err,doc){
		if(err){
			return err;
		}
		return res.json({code:0,content:doc});
	})
});

Router.post('/update',function(req,res){
	const userid = req.cookies.userid;
	if(!userid){
		return res.json({code:1,msg:'无效cookie'});
	}
	const body = req.body;
	User.findByIdAndUpdate(userid,body,function(err,doc){
		if (err) {
			console.log(err);
			return res.json({code:1,msg:'后端出错'});
		}
		if (doc) {
			const content = Object.assign({},{user:doc.user,type:doc.type},body);
			return res.json({content,code:0});
		}
	});
	
});


Router.post('/login',function(req,res){
	console.log(req.body);
	const {user,pwd} = req.body;
	User.findOne({user,pwd:md5Pwd(pwd)},_filter,function(err,doc){
		if (doc) {
			res.cookie('userid',doc._id);
			return res.json({code:0,content:doc});
		}else{
			return res.json({code:1,msg:'用户名或者密码错误'});
		}
	})
});

Router.post('/register',function(req,res){
	const {user,pwd,type} = req.body;
	User.findOne({user},function(err,doc){
		if (doc) {
			return res.json({code:1,msg:'用户名重复'});
		}
		
		const userModel = new User({user,type,pwd:md5Pwd(pwd)});
		userModel.save(function(err,doc){
			if (err) {
				return res.json({code:1,msg:'后端出错了'});
			}
			res.cookie('userid',doc._id);
			const {user,type,_id} = doc;
			return res.json({code:0,content:{user,type,_id}});

		});
	})
});
Router.get('/info',function(req,res){
	const {userid} = req.cookies;
	if(!userid){
		return res.json({code:1,msg:'无效cookie'});
	}
	
	User.findOne({_id:userid},_filter,function(err,doc){
		if (err) {
			return res.json({code:1,msg:'后端出错'});
		}
		if (doc) {
			return res.json({code:0,content:doc});
		}
	});
	
});

Router.get('/msglist',function(req,res){
	const userid = req.cookies.userid;
	
	User.find({},function(usererr,userdoc){
		if (!usererr) {
			let users = {};
			userdoc.forEach(v => {
				users[v._id] = {user:v.user,avatar:v.avatar};
			});
			Chat.find({'$or':[{from:userid},{to:userid}]},function(err,doc){
				if (err) {
					return res.json({code:1,msg:'后端出错'});
				}
				
				if (doc) {
					return res.json({code:0,content:{msgs:doc,users:users}});
				}
			});
		} 
	});	
});

Router.post('/readmsg',function(req,res){
	const userid = req.cookies.userid;
	const from  = req.body.from;
	Chat.update({from,to:userid},{'$set':{read:true}},{'multi':true},function(err,doc){
		if (!err) {
			console.log(doc);
			return res.json({code:0,content:{number:doc.nModified}});
		}
		return res.json({code:1});
	});
});



module.exports = Router;